﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using mBlogAPI.BL;
using mBlogAPI.Schema;
using mBlogAPI.Utils;

namespace MyDesktopMicroBlog.Converter.StatusHelper
{
    public class StatusHelper : DependencyObject
    {
        public static TwoArgsDelegate<Status,bool> OnStatusUpdate;
        public string Status
        {
            get { return (string)GetValue(StatusProperty); }
            set { SetValue(StatusProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Status.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty StatusProperty =
            DependencyProperty.Register("Status", typeof(string), typeof(StatusHelper), new FrameworkPropertyMetadata("在此处输入可以发表微博哦...",
                OnStatusChanged));

        private static void OnStatusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            bool IsSuccess = false;
            try
            {
                if (!string.IsNullOrWhiteSpace(e.NewValue.ToString()) && e.NewValue != e.Property.DefaultMetadata.DefaultValue)
                {
                    try
                    {
                        Status status = StatusesBL.UpdateMyStatus(e.NewValue.ToString());
                        if (OnStatusUpdate != null && status != null)
                        {
                            OnStatusUpdate(status, true);
                            IsSuccess = true;
                        }
                    }
                    catch
                    {
                    }
                }
            }
            catch
            {
                d.ClearValue(StatusProperty);
            }

            if (IsSuccess == false)
            {
                OnStatusUpdate(null, false);
            }
        }

        public static bool InsertStatusToMainWindow(Status status)
        {
            try
            {
                (Application.Current.MainWindow as MainWindow).Dispatcher.BeginInvoke(
                    new OneArgDelegate<Status>((s)=>{
                        (App.Current.MainWindow as MainWindow).InsertStatusToMainWindow(status, true);
                    }
                    ), status);
                return true;
            }
            catch(Exception ex)
            {
                LogHelper.LogError(ex);
                return false;
            }
        }
    }
}
